﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using PaceR.Data.Transactions;

namespace PaceR.Data.Context
{
    public abstract class BaseContext
    {
        protected readonly BaseTransactionManager _transactionManager;

        public BaseContext(BaseTransactionManager transactionManager)
        {
            if (transactionManager == null) throw new ArgumentNullException("transactionManager");
            _transactionManager = transactionManager;
        }

        public abstract IQueryable<T> Find<T>();

        public abstract IQueryable<T> Find<T>(Func<T, bool> where);

        public abstract T First<T>(Func<T, bool> where);

        public abstract T FirstOrDefault<T>(Func<T, bool> where);

        public abstract void Save<T>(T record);

        public abstract void Remove<T>(T record);

        public virtual void RemoveResults<T>(Func<IQueryable<T>, IEnumerable<T>> query)
        {
            foreach (T record in query(Find<T>()))
            {
                Remove(record);
            }
        }

        public virtual void Commit()
        {
            _transactionManager.Commit();
        }

        public virtual void Rollback()
        {
            _transactionManager.Rollback();
        }
    }
}
